//
//  KImageSelect.swift
//  ZDKBaseKit
//
//  Created by Killua on 2017/9/22.
//  Copyright © 2017年 JingZhong. All rights reserved.
//

import UIKit

@objc protocol KImageSelectProtocol: NSObjectProtocol {
    @objc optional func selectedImage(_ image: UIImage)
}

class KImageSelect: NSObject {

    weak var presentedController: UIViewController?

    weak var delegate: KImageSelectProtocol?

    /// 弹出获取照片的途径
    ///
    /// - Parameters:
    ///   - canEdit: 照片是否可编辑
    ///   - title: sheet title
    ///   - message: 描述
    ///   - cameraTitle: 相机标题
    ///   - albumTitle: 相册标题
    ///   - cancelTitle: 取消标题
    func showActionSheet(canEdit: Bool, title: String, message: String, cameraTitle: String, albumTitle: String, cancelTitle: String) {
        let control = UIAlertController.init(title: title, message: message, preferredStyle: .actionSheet)

        let camera = UIAlertAction.init(title: cameraTitle, style: .default, handler: { (action) in
            self.pickImage(sourceType: .camera, canEdit: canEdit)
        })

        let album = UIAlertAction.init(title: albumTitle, style: .default, handler: { (action) in
            self.pickImage(sourceType: .photoLibrary, canEdit: canEdit)
        })

        let cancel = UIAlertAction.init(title: cancelTitle, style: .cancel, handler: { (action) in
        })

        control.addAction(camera)
        control.addAction(album)
        control.addAction(cancel)
        self.presentedController?.present(control, animated: true, completion: nil)
    }

    private func pickImage(sourceType: UIImagePickerControllerSourceType, canEdit: Bool) {
        if sourceType == .camera {
            guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
                return
            }
        }

        let imagePicker = UIImagePickerController.init()
        imagePicker.delegate = self
        imagePicker.sourceType = sourceType
        imagePicker.modalTransitionStyle = .coverVertical
        imagePicker.allowsEditing = canEdit


        self.presentedController?.present(imagePicker, animated: true, completion: nil)
    }

    func imageWithImageSimple(_ image: UIImage, scaleSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContext(scaleSize)

        let frame = CGRect.init(x: 0, y: 0, width: scaleSize.width, height: scaleSize.height)
        image.draw(in: frame)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

    func saveImage(_ image: UIImage, name: String) -> String {

        var fullPath: String = ""
        if let imageData = UIImagePNGRepresentation(image) as NSData? {
            fullPath = NSHomeDirectory().appending("/Documents/").appending(name)
            imageData.write(toFile: fullPath, atomically: true)
        }

        return fullPath
    }
}

extension KImageSelect: UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        var image: UIImage
        if picker.allowsEditing {
            image = info[UIImagePickerControllerEditedImage] as! UIImage
        } else {
            image = info[UIImagePickerControllerOriginalImage] as! UIImage
        }
        // 将拍照图片存入手机相册
        if picker.sourceType == UIImagePickerControllerSourceType.camera {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        }

        let selector = #selector(KImageSelectProtocol.selectedImage(_:))
        if let cDeletage = self.delegate {
            if cDeletage.responds(to: selector) {
                cDeletage.selectedImage!(image)
            }
        }

        self.presentedController?.dismiss(animated: true, completion: nil)
    }
}

extension KImageSelect: UINavigationControllerDelegate {

}
